package com.yjx.managedemo.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yjx.managedemo.entity.Admins;
import com.yjx.managedemo.mapper.AdminsDao;
import com.yjx.managedemo.po.AdminQuery;
import com.yjx.managedemo.re.PageResult;
import com.yjx.managedemo.service.AdminsService;
import com.yjx.managedemo.util.MD5Util;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AdminServiceImpl implements AdminsService {
    @Resource
    private AdminsDao adminsDao;

    @Override
    public Admins queryById(Integer adminId) {
        var admins = new Admins();
        admins = adminsDao.queryById(adminId);
        return admins;
    }

    @Override
    public PageResult queryAllByLimit(AdminQuery adminQuery) {
        PageHelper.startPage(adminQuery.getPage(),adminQuery.getLimit());
        PageInfo<Admins> pageInfo =new PageInfo<>(adminsDao.list(adminQuery));
        PageResult<Admins> pageResult = new PageResult<>();
        pageResult.setCode(0);
        pageResult.setCount((int) pageInfo.getTotal());
        pageResult.setMsg("");
        pageResult.setData(pageInfo.getList());
        return pageResult;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Admins insert(Admins admins) {
        admins.setPassword(MD5Util.MD5Encode(admins.getPassword(), "utf-8"));
        adminsDao.insert(admins);
        admins = adminsDao.login(admins);
        return admins;
    }

    @Override
    public Admins update(Admins admins) {
        Integer index = adminsDao.update(admins);
        if(index>0){
            admins = adminsDao.login(admins);
            return admins;
        }
        return null;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public int deleteById(Integer adminId) {
        return adminsDao.deleteById(adminId);
    }

    @Override
    public Admins login(String name, String password) {
        Admins admins = new Admins();
        admins.setName(name);
        password= MD5Util.MD5Encode(password,"utf-8");
        admins.setPassword(password);
        admins = adminsDao.login(admins);
        return admins;
    }
}
